from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from app.config import create_db_connection

list_customers_bp = Blueprint('list_customers', __name__)


@list_customers_bp.route('/list_customer', endpoint='list_customer')
def customer_list():
    conn, cursor = create_db_connection()
    # 使用数据库连接执行 SQL 查询语句获取客户列表数据
    cursor.execute("SELECT * FROM customer_list")
    rows = cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template('customer/list_customer.html', rows=rows)


@list_customers_bp.route('/edit_customer', methods=['GET', 'POST'])
def edit_customer():
    if request.method == 'GET':
        # 获取客户ID参数并进行相应的处理
        customer_id = request.args.get('id')
        conn, cursor = create_db_connection()
        # 根据客户ID执行查询操作，获取客户信息
        cursor.execute("SELECT * FROM customer_list WHERE id = %s", (customer_id,))
        customer = cursor.fetchone()
        # 返回编辑客户信息的页面，并将客户信息传递给模板
        return render_template('customer/edit_customer.html', customer=customer)
    elif request.method == 'POST':
        # 获取客户ID和更新后的客户信息
        customer_id = request.form.get('id')
        updated_name = request.form.get('companyName')
        updated_credit_code = request.form.get('creditCode')
        updated_address = request.form.get('address')
        updated_contact_person = request.form.get('contactPerson')
        updated_contact_number = request.form.get('contactNumber')
        conn, cursor = create_db_connection()
        # 根据客户ID执行更新操作
        cursor.execute(
            "UPDATE customer_list SET customer_name = %s, creditCode = %s, address = %s, contactPerson = %s, contactNumber = %s WHERE id = %s",
            (updated_name, updated_credit_code, updated_address, updated_contact_person, updated_contact_number,
             customer_id))
        conn.commit()
        cursor.close()
        conn.close()
        # 返回客户列表页面
        return redirect('/list_customer')


@list_customers_bp.route('/delete_customer/<int:customer_id>', methods=['POST'])
def delete_customer(customer_id):
    # 根据客户ID执行删除操作
    conn, cursor = create_db_connection()
    cursor.execute("DELETE FROM customer_list WHERE id = %s", (customer_id,))
    conn.commit()
    cursor.close()
    conn.close()
    # 返回客户列表页面
    return redirect('/list_customer')
